package com.hefan.oms.dao;

import com.alibaba.fastjson.JSON;
import com.hefan.common.exception.DataIllegalException;
import com.hefan.common.orm.dao.BaseDaoImpl;
import com.hefan.oms.bean.WebUserIncome;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * Created by hbchen on 2016/10/8.
 */
@Repository
public class InComeDao extends BaseDaoImpl<WebUserIncome> {

  @Resource
  private JdbcTemplate jdbcTemplate;

  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public long insertNewRecord(WebUserIncome record) throws Exception {

    record = super.save(record);

    if (record.getId() <= 0) {
      throw new DataIllegalException(String.format("保存用户收入失败%s", JSON.toJSONString(record)));
    }
    return record.getId();

  }

  public List<Map<String, Object>> getTotalByLiveUuid(String liveUuid) {
    return jdbcTemplate.queryForList("select sum(hefan_num) hefanNum,type from web_user_income where live_uuid=? and source=0 and delete_flag=0 and is_old=1 GROUP BY type", new Object[] { liveUuid });
  }

  public List<Map<String, Object>> getUserIncomeByDay(String start, String end) {
    return jdbcTemplate.queryForList("select sum(hefan_num) hefanNum,type,user_id userId from web_user_income where create_time BETWEEN ? and ? and source<2 and delete_flag=0 and is_old=1 GROUP BY user_id,type",
        new Object[] { start, end });
  }
}
